'use strict';

const BaseService = require('./base');
const modelName = 'Product';
class RouterService extends BaseService {
  constructor(ctx) {
    super(ctx, modelName);
  }

  pageOrder() {
    let query = this.ctx.query;
    let order = [];
    if (query.order_price) {
      order.push(['price', query.order_price])
    }
    if (query.order_sales) {
      order.push(['sales', query.order_sales])
    }
    return order
  }
  pageInclude() {
    return [
      {
        model: this.ctx.model.ProductItem,
        as: 'items',
      }
    ]
  }
  showInclude() {
    return [
      {
        model: this.ctx.model.ProductItem,
        as: 'items',
      }
    ]
  }
  pageInclude() {
    return [
      {
        model: this.ctx.model.ProductItem,
        as: 'items',
      },
      {
        model: this.ctx.model.Category,
        as: 'category',
      }
    ]
  }
  async create(data) {
    delete data.id
    // 创建事务
    const transaction = await this.ctx.model.transaction();
    try {
      // 创建主商品
      const product = await this.ctx.model.Product.create({
        ...data,
      }, {
        transaction
      });
      // 创建商品项
      await this.ctx.model.ProductItem.create({
        ...data,
        product_id: product.id
      }, {
        transaction
      });
      await transaction.commit();
      return product
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }
  async update(id, data) {
    // 创建事务
    const transaction = await this.ctx.model.transaction();
    try {
      // 更新主商品
      const product = await this.ctx.model.Product.update({
        ...data,
      }, {
        where: {id},
        include: [
          {
            model: this.ctx.model.ProductItem,
            as: 'items',
          }
        ],
        transaction
      });
      // 更新商品项
      await this.ctx.model.ProductItem.update({
        ...data,
        id: undefined
      }, {
        where: {
          product_id: id
        },
        transaction
      });
      await transaction.commit();
      return product
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }

  async findOne(id) {
    const productItem = await this.ctx.model.ProductItem.findOne({
      where: {
        product_id: id
      },
    });
    const product = await this.ctx.model.Product.findOne({
      where: {
        id
      },
    });

    return {
      ...productItem.dataValues,
      id: product.dataValues.id,
      product_id: undefined,
      type: product.dataValues.type,
      category_id: product.dataValues.category_id,
    }
  }

  async deleteById(id) {
    await this.ctx.model[this.modelName].destroy({ where: { id } });
    await this.ctx.model.ProductItem.destroy({ where: { product_id: id } });
    return true
  }
}


module.exports = RouterService;
